<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <TimeFiltering @time-filter-value="getTimeFilterValue" />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column?.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:eye-filled',
                tooltip: {
                  title: '详情',
                  placement: 'top',
                },
                onClick: openDetails.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <BasicModal
      v-bind="$attrs"
      @register="register"
      title="审计日志详情"
      :helpMessage="['提示1', '提示2']"
    >
      <div>
        <span>活动数据</span>
        <JsonPreview :data="securityDataItem.actionData" />
      </div>
      <div
        v-show="
          securityDataItem.actionFailureDetails !== '' &&
          securityDataItem.actionFailureDetails !== null
        "
      >
        <span>失败详情</span>
        <div :style="jsonStyle">{{ securityDataItem.actionFailureDetails }}</div>
      </div>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  /**
   * 获取指定数据审计日志 使用组件通信 传入用户 id对象 "id": {"entityType": "ASSET", "id": "09167ac0-b5aa-11ee-8452-eb7b38a2de3e"},
   * **/
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { JsonPreview } from '/@/components/CodeEditor';
  import {
    securityColumns,
    searchFormSchema,
  } from '/@/views/thingsborad/security/components/security.data';
  import TimeFiltering from '/@/components/thingsborad/sharedComponents/modules/TimeFiltering.vue';
  import { getSecurityList, getSecurityListById } from '/@/api/thingsborad/security/security';
  import { onMounted, ref, watch } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import dayjs from 'dayjs';
  import {
    tableFormStyleSetting,
    tableStyleSetting,
    publicDrawerTableFormStyleSetting,
  } from '/@/settings/thingsBoardDesign';
  import { securityParams } from '/@/api/thingsborad/security/model/securityModel';
  const props = defineProps(['paramsId']);
  watch(
    () => props.paramsId,
    (nVal) => {
      params.value.startTime = dayjs().valueOf() - 24 * 60 * 60 * 1000;
      // 当前时间戳
      params.value.endTime = dayjs().valueOf();
      let paramsById: any = {
        route: 'entity',
        id: nVal,
        params: params.value,
      };
      setProps({
        formConfig: {
          layout: 'horizontal',
          schemas: searchFormSchema,
          showAdvancedButton: false,
          submitFunc: async () => {
            reload();
          },
          ...publicDrawerTableFormStyleSetting,
          actionColOptions: {
            md: { span: 12, offset: 0 },
            lg: { span: 8, offset: 8 },
            xl: { span: 6, offset: 12 },
            xxl: { span: 6, offset: 12 },
          },
        },
        api: getSecurityListById,
        beforeFetch: (val) => {
          params.value.page = val.page - 1;
          params.value.pageSize = val.pageSize;
          params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
          params.value.sortProperty = 'createdTime';

          if (val.deptName === null) {
            params.value.textSearch = undefined;
          } else {
            params.value.textSearch = val.deptName;
          }
          return paramsById;
        },
        afterFetch: (res) => {
          securityDataList.value = [];
          if (res.length === 0) {
            return securityDataList.value;
          }
          res.forEach((item) => {
            securityDataList.value.push({
              createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
              entityType: item.entityId.entityType,
              entityName: item.entityName,
              userName: item.userName,
              actionType: item.actionType,
              actionStatus: item.actionStatus,
              actionData: item.actionData,
              actionFailureDetails: item.actionFailureDetails,
            });
          });
          return securityDataList.value;
        },
        fetchSetting: {
          pageField: 'page',
          sizeField: 'pageSize',
          listField: 'data',
          totalField: 'totalElements',
        },
      });
    },
  );
  const [register, { openModal, setModalProps }] = useModal();
  //请求参数
  let params = ref<securityParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
  });
  // 审计安全表格数据
  let securityDataList = ref<Array<any>>([]);
  // 活动数据
  let securityDataItem = ref<any>();
  // 生命后期函数
  onMounted(() => {
    // 初始化表格数据
    // 24小时前的时间戳
    params.value.startTime = dayjs().valueOf() - 24 * 60 * 60 * 1000;
    // 当前时间戳
    params.value.endTime = dayjs().valueOf();
    let apiName: any;
    let paramsById: any;
    if (props.paramsId === undefined) {
      // 后端数据接口请求
      apiName = 'getSecurityList';
    } else {
      paramsById = {
        route: 'entity',
        id: props.paramsId,
        params: params.value,
      };
      apiName = 'getSecurityListById';
    }
    setProps({
      formConfig: {
        layout: 'horizontal',
        schemas: searchFormSchema,
        showAdvancedButton: false,
        submitFunc: async () => {
          reload();
        },
        ...tableFormStyleSetting,
        actionColOptions:
          apiName === 'getSecurityList'
            ? {
                md: { span: 8, offset: 16 },
                lg: { span: 6, offset: 16 },
                xl: { span: 4, offset: 16 },
                xxl: { span: 4, offset: 16 },
              }
            : {
                md: { span: 12, offset: 0 },
                lg: { span: 8, offset: 12 },
                xl: { span: 6, offset: 12 },
                xxl: { span: 6, offset: 12 },
              },
      },
      api: apiName === 'getSecurityList' ? getSecurityList : getSecurityListById,
      beforeFetch: (val) => {
        params.value.page = val.page - 1;
        params.value.pageSize = val.pageSize;
        params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
        params.value.sortProperty = 'createdTime';

        if (val.deptName === null) {
          params.value.textSearch = undefined;
        } else {
          params.value.textSearch = val.deptName;
        }
        return apiName === 'getSecurityList' ? params.value : paramsById;
      },
      afterFetch: (res) => {
        securityDataList.value = [];
        if (res.length === 0) {
          return securityDataList.value;
        }
        res.forEach((item) => {
          securityDataList.value.push({
            createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
            entityType: item.entityId.entityType,
            entityName: item.entityName,
            userName: item.userName,
            actionType: item.actionType,
            actionStatus: item.actionStatus,
            actionData: item.actionData,
            actionFailureDetails: item.actionFailureDetails,
          });
        });
        return securityDataList.value;
      },
      fetchSetting: {
        pageField: 'page',
        sizeField: 'pageSize',
        listField: 'data',
        totalField: 'totalElements',
      },
    });

    // 初始化弹窗
    setModalProps({
      showOkBtn: false,
      cancelText: '关闭',
    });
  });
  //表格初始化
  const [registerTable, { setPagination, getForm, setProps, reload }] = useTable({
    columns: securityColumns,
    ...tableStyleSetting,
  });
  // 详情
  function openDetails(record: Recordable) {
    openModal(true, true);
    securityDataItem.value = record;
  }
  async function getSecurityData(params: any) {
    securityDataList.value = [];
    try {
      let securityData: any;
      if ('params' in params) {
        securityData = await getSecurityListById(params);
      } else {
        securityData = await getSecurityList(params);
      }
      setPagination({
        showQuickJumper: true,
        pageSizeOptions: ['10', '20', '30', '40'],
        total: securityData.totalElements,
        showTotal: (total) => `共 ${total} 条数据`,
      });
      securityData.data.forEach((item) => {
        securityDataList.value.push({
          createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
          entityType: item.entityId.entityType,
          entityName: item.entityName,
          userName: item.userName,
          actionType: item.actionType,
          actionStatus: item.actionStatus,
          actionData: item.actionData,
          actionFailureDetails: item.actionFailureDetails,
        });
      });
    } catch (error) {
      console.error('获取数据时出错：', error);
      // 处理错误情况
    }
  }
  const jsonStyle = ref<any>({
    border: '1px solid #C0C0C0',
    borderRadius: '5px',
    padding: '5px',
    marginTop: '5px',
  });
  function getTimeFilterValue(timestamp) {
    params.value.startTime = timestamp.startTimestamp;
    // 当前时间戳
    params.value.endTime = timestamp.endTimestamp;
    // 后端数据接口请求
    setProps({
      formConfig: {
        layout: 'horizontal',
        schemas: searchFormSchema,
        showAdvancedButton: false,
        submitFunc: async () => {
          reload();
        },
        ...tableFormStyleSetting,
        actionColOptions: {
          md: { span: 8, offset: 16 },
          lg: { span: 6, offset: 16 },
          xl: { span: 4, offset: 16 },
          xxl: { span: 4, offset: 16 },
        },
      },
      api: getSecurityList,
      beforeFetch: (val) => {
        params.value.page = val.page - 1;
        params.value.pageSize = val.pageSize;
        params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
        params.value.sortProperty = 'createdTime';

        if (val.deptName === null) {
          params.value.textSearch = undefined;
        } else {
          params.value.textSearch = val.deptName;
        }
        return params.value;
      },
      afterFetch: (res) => {
        securityDataList.value = [];
        if (res.length === 0) {
          return securityDataList.value;
        }
        res.forEach((item) => {
          securityDataList.value.push({
            createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
            entityType: item.entityId.entityType,
            entityName: item.entityName,
            userName: item.userName,
            actionType: item.actionType,
            actionStatus: item.actionStatus,
            actionData: item.actionData,
            actionFailureDetails: item.actionFailureDetails,
          });
        });
        return securityDataList.value;
      },
      fetchSetting: {
        pageField: 'page',
        sizeField: 'pageSize',
        listField: 'data',
        totalField: 'totalElements',
      },
    });
    reload();
  }
</script>
